<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.testTitle"
          placeholder="测试标题"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleFilter"
        />
        <!-- 只有管理员和超级管理员可以看到用户名搜索框 -->
        <el-input
          v-if="isAdmin"
          v-model="listQuery.username"
          placeholder="用户名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleFilter"
        />
        <el-select
          v-model="listQuery.level"
          placeholder="评估等级"
          clearable
          style="width: 200px"
          class="filter-item"
        >
          <el-option label="正常" value="正常" />
          <el-option label="轻度抑郁" value="轻度抑郁" />
          <el-option label="中度抑郁" value="中度抑郁" />
          <el-option label="重度抑郁" value="重度抑郁" />
        </el-select>
        <el-button class="filter-item" type="primary" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" @click="resetQuery">
          重置
        </el-button>
      </div>

      <!-- 测试结果列表 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
      >
        <el-table-column label="测试标题" prop="testTitle" align="center" />
        <el-table-column label="用户名" prop="username" align="center" />
        <el-table-column label="总分" prop="totalScore" align="center" />
        <el-table-column label="评估等级" prop="level" align="center">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分析建议" align="center">
          <template #default="scope">
            <el-tooltip :content="scope.row.analysis" placement="top">
              <span>{{ scope.row.analysis?.slice(0, 20) }}{{ scope.row.analysis?.length > 20 ? '...' : '' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="评审状态" align="center">
          <template #default="scope">
            <el-tooltip v-if="scope.row.reviewedBy" :content="`评审人: ${scope.row.reviewerName || '未知'}\n评审时间: ${formatTime(scope.row.reviewTime)}\n评审意见: ${scope.row.reviewComments || '无'}`" placement="top">
              <el-tag type="success">已评审</el-tag>
            </el-tooltip>
            <el-tag v-else type="info">未评审</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="测试时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="测试用时" align="center">
          <template #default="{ row }">
            {{ formatDuration(row.testDuration) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-show="total > 0"
        :current-page="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>
import { getTestResultList, getTestRecordDetail } from '../../api/psychological-test'
import { formatTime, formatDateTime, formatDuration } from '../../utils/format'
import { mapGetters } from 'vuex'

export default {
  name: 'TestResultList',
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        testTitle: '',
        username: '',
        level: ''
      }
    }
  },
  computed: {
    ...mapGetters({
      userInfo: 'user/userInfo'
    }),
    isAdmin() {
      const role = this.userInfo?.role?.toLowerCase()
      return role === 'admin' || role === 'superadmin'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getLevelTagType(level) {
      const types = {
        '正常': '',
        '轻度抑郁': 'warning',
        '中度抑郁': 'danger',
        '重度抑郁': 'danger'
      }
      return types[level] || 'info'
    },
    async getList() {
      this.listLoading = true
      try {
        const response = await getTestResultList({
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize,
          testTitle: this.listQuery.testTitle,
          username: this.listQuery.username,
          level: this.listQuery.level
        })
        if (response.code === 200) {
          this.list = response.data.records
          this.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取列表失败')
        }
      } catch (error) {
        console.error('获取测试结果列表失败:', error)
        this.$message.error('获取列表失败，请重试')
      } finally {
        this.listLoading = false
      }
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    formatTime,
    formatDateTime,
    formatDuration,
    async handleDetail(row) {
      try {
        const response = await getTestRecordDetail(row.recordId)
        if (response.code === 200) {
          this.$router.push({
            path: `/test/result/${row.recordId}`,
            query: { from: 'test-result-list' }
          })
        } else {
          this.$message.error(response.msg || '获取测试记录失败')
        }
      } catch (error) {
        console.error('获取测试记录失败:', error)
        this.$message.error('获取测试记录失败，请重试')
      }
    },
    resetQuery() {
      this.listQuery = {
        pageNum: 1,
        pageSize: 10,
        testTitle: '',
        username: '',
        level: ''
      }
      this.getList()
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
</style> 